package jp.eisbahn.mgapi.api;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import jp.eisbahn.mgapi.auth.Token;
import jp.eisbahn.mgapi.http.HttpFetcher;
import jp.eisbahn.mgapi.http.HttpRequest;
import jp.eisbahn.mgapi.http.HttpResponse;
import jp.eisbahn.mgapi.http.HttpUtils;

public class Client {
    
    public static final String URL = "http://api.mixi-platform.com/2";
    
    private HttpFetcher httpFetcher;

    public void setHttpFetcher(HttpFetcher httpFetcher) {
        this.httpFetcher = httpFetcher;
    }

    @SuppressWarnings("unchecked")
    public <T extends Response> T send(Token token, Request request)
            throws ApiAccessException, IOException {
        HttpRequest httpRequest = createHttpRequest(token, request);
        HttpResponse httpResponse = httpFetcher.fetch(httpRequest);
        if (HttpUtils.isSuccess(httpResponse)) {
            Response response = createResponse(request);
            response.parseResponse(httpResponse);
            return (T)response;
        } else {
            throw new ApiAccessException(httpResponse);
        }
    }
    
    private Response createResponse(Request request) {
        try {
            Class<? extends Response> clazz = request.getResponseClass();
            Response response = clazz.newInstance();
            return response;
        } catch(IllegalAccessException e) {
            throw new IllegalStateException(e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(e);
        }
    }

    private HttpRequest createHttpRequest(Token token, Request request) {
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Authorization", "OAuth " + token.getAccessToken());
        HttpRequest httpRequest = new HttpRequest(
                URL + request.getUri(),
                null,
                request.getHttpMethod(),
                request.getContentType(),
                headerMap);
        return httpRequest;
    }
    
}
